<template>
  <div class="user h-full px-4 py-3 rounded-lg">
    <div class="user-content">
      <div class="user-condition">
        <div>
          <a-button
            v-permission="'/systemConfig/user/user-add'"
            class="user-condition-button2 ghost [@media(max-width:1366px)]:!w-40 ml-0"
            @click="openEditModal(false)"
          >
            添加用户
          </a-button>
        </div>
        <div class="right">
          <a-tree-select
            @select="changeOrganize"
            class="user-condition-select"
            placeholder="全部所属机构"
            allow-clear
            tree-default-expand-all
            :tree-data="organizationList"
            v-model:value="organization"
            :field-names="{
              children: 'children',
              label: 'name',
              value: 'id'
            }"
          >
            <template #title="{ label }">
              <div :title="label" class="ellipsis-label">
                <!-- {{ label && label.length > 8 ? label.slice(0, 8) + '...' : label }} -->
                {{ label }}
              </div>
            </template>
          </a-tree-select>
          <a-select
            class="user-condition-select"
            v-model:value="role"
            allow-clear
            placeholder="全部角色"
            :options="
                    roleList.map((item:any) => ({
                      label: item.roleName,
                      value: item.roleId
                    }))
                  "
          />
          <a-input
            class="user-condition-input"
            v-model:value="username"
            placeholder="请输入用户名"
            @keyup.enter="getUser(true)"
            maxLength="20"
            v-filter-special-chars
          />
          <!-- <a-button @click="getUser(true)" type="submit" class="search">
            <template #icon>
              <SearchOutlined />
            </template>
          </a-button>
          <a-button @click="reset" type="submit" class="refresh">
            <template #icon>
              <ReloadOutlined />
            </template>
          </a-button> -->
          <SerchButtom @search="getUser(true)" @reset="reset" />
        </div>
      </div>
      <div class="user-table">
        <a-table
          :dataSource="dataSource"
          :columns="columns"
          :pagination="false"
          :loading="loading"
        >
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.dataIndex === 'operation'">
              <div class="flex justify-start">
                <a-button
                  type="link"
                  @click="resetPassword(record)"
                  v-permission="'/systemConfig/user/user-resetpass'"
                  >重置密码</a-button
                >
                <a-button
                  v-if="record.userName !== 'admin'"
                  type="link"
                  @click="openEditModal(record)"
                  v-permission="'/systemConfig/user/user-edit'"
                  >修改</a-button
                >
                <!-- <a-button
                  type="sm-orange"
                  v-permission="'/systemConfig/user/user-disable'"
                  v-if="record.userName !== 'superAdmin'"
                  @click="forbiddenUser(record)"
                  class="mr-4"
                >
                  {{ +record.status === 1 ? '恢复' : '禁用' }}
                </a-button> -->
                <a-button
                  v-permission="'/systemConfig/user/user-delete'"
                  v-if="record.userName !== 'admin'"
                  type="link"
                  class="delete"
                  @click="deleteUser(record)"
                  >删除</a-button
                >
              </div>
            </template>
            <template v-else-if="column.dataIndex === 'order'">
              {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
            </template>
          </template>
        </a-table>
      </div>
      <div class="user-pagination">
        <Pagination @getListByPage="getListByPage" ref="paginationRef" />
      </div>
    </div>
  </div>
  <user-modal
    ref="addUserModal"
    :organizationList="organizationList"
    :roleList="roleList"
    :modalType="modalType"
    @isOk="getUser"
    :forbiddenType="forbiddenType"
  />
</template>

<script lang="ts" setup>
import type { User } from '@/api/model/user'
import { getOrgTree } from '@/api/organization'
import { getRoleOptionList } from '@/api/role'
import { getUserList } from '@/api/user'
import { onMounted, reactive, ref } from 'vue'
import UserModal from './UserModal.vue'
import { message } from 'ant-design-vue'
import { hasPermission } from '@/utils/permession'
// import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue'

import SerchButtom from '@/components/YuanQi-SearchButtom.vue'

const username = ref()
const loading = ref<boolean>(false)
const forbiddenType = ref<boolean>(true)
const dataSource = ref()
const deptType = ref()

const columns = ref([
  {
    title: '序号',
    width: '7.5rem',
    dataIndex: 'order'
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    ellipsis: true
  },
  {
    title: '角色',
    dataIndex: 'roleName',
    key: 'roleName',
    ellipsis: true
  },
  {
    title: '姓名',
    dataIndex: 'nickName',
    key: 'nickName',
    ellipsis: true
  },
  {
    title: '所属机构',
    dataIndex: 'deptName',
    key: 'deptName',
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    ellipsis: true,
    width: 185
  }
])

const pagination = reactive({
  total: 0,
  pageSize: 10, // 每页中显示10条数据
  position: ['bottomCenter'],
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`
})

// 组织机构
const organization = ref()
const organizationList = ref([])
const getDeptTree = () => {
  getOrgTree().then((res) => {
    if (!res) return
    organizationList.value = res
  })
}

// 角色
const roleList = ref([])
const role = ref()
const getOptionSelect = () => {
  getRoleOptionList().then((res) => {
    if (!res) return
    roleList.value = res
  })
}

// 用户
const getUser = (flag = false) => {
  if (flag) {
    pagination.current = 1
    paginationRef.value.changeCurrent(pagination.current)
  }
  loading.value = true
  dataSource.value = []
  getUserList({
    roleId: role.value,
    deptId: organization.value?.toString().split('#')[0],
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
    username: username.value ?? '',
    deptType: organization.value ? deptType.value : undefined
  })
    .then((res) => {
      if (!res) return (loading.value = false)
      dataSource.value = res.list
      pagination.total = res.total
      paginationRef.value.changeTotal(pagination.total)
      loading.value = false
      if (res.list.length === 0 && pagination.current !== 1) {
        pagination.current--
        paginationRef.value.changeCurrent(pagination.current)
        getUser(false)
      }
    })
    .catch(() => {
      message.error('获取数据失败！')
      loading.value = false
    })
}

const init = () => {
  getDeptTree()
  getOptionSelect()
  getUser()
}

onMounted(() => {
  init()
  const flag =
    hasPermissionFun('/systemConfig/user/user-resetpass') ||
    hasPermissionFun('/systemConfig/user/user-edit') ||
    hasPermissionFun('/systemConfig/user/user-delete')
  if (!flag) {
    columns.value.pop()
  }
})

const hasPermissionFun = (path: string) => {
  return hasPermission(path)
}

const resetPassword = (data: User) => {
  modalType.value = 'resetPassword'
  addUserModal.value.showModal(data)
}

const openEditModal = (data: User | false) => {
  data ? (modalType.value = 'edit') : (modalType.value = 'add')
  addUserModal.value.showModal(data)
}

// const forbiddenUser = (data: User) => {
//   const flag = data.status && +data.status === 0
//   if (flag) {
//     forbiddenType.value = true
//   } else {
//     forbiddenType.value = false
//   }

//   modalType.value = 'forbidden'
//   addUserModal.value.showModal(data)
// }

const deleteUser = (data: User) => {
  modalType.value = 'delete'
  addUserModal.value.showModal(data)
}

// 模态框
type ModalType = 'delete' | 'add' | 'edit' | 'resetPassword'
const modalType = ref<ModalType>('delete')
const addUserModal = ref()
const paginationRef = ref()
const getListByPage = (page: number, pageSize: number) => {
  if (pagination.current !== page) {
    pagination.current = page
    getUser()
  }
  if (pagination.pageSize !== pageSize) {
    pagination.pageSize = pageSize
    getUser(true)
  }
}

const changeOrganize = (value: any, node: { type: number | undefined }) => {
  deptType.value = node.type
}

const reset = () => {
  organization.value = undefined
  role.value = undefined
  username.value = undefined
  getUser(true)
}
</script>

<style lang="less" scoped>
/* stylelint-disable-next-line string-quotes */
@import './user.less';
</style>
